<template>
  <div class="tabs-main">
    <a-tabs
      v-model="tabValue"
      :tabBarStyle="{ backgroundColor: '#fff', marginBottom: '6px', padding: '0px 8px' }"
      v-if="tabsItems && tabsItems.length > 0"
      @change="changeTabs"
    >
      <a-tab-pane v-for="item in tabsItems" :tab="item.title" :key="item.key" />
    </a-tabs>
    <a-row type="flex" style="flex-flow: inherit" v-if="reloading">
      <a-col :flex="toggle ? '260px' : '30px'" style="margin-right: 12px; background-color: #fff">
        <depart-tree :rootOpened="true" :multi="false" @ok="getTreeData" @toggleBool="toggleBool" />
      </a-col>
      <a-col flex="auto">
        <a-card :bordered="false" style="margin-bottom: 10px">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
              <z-form-item
                :datas="fieldArr"
                :form="queryParam"
                :gutter="8"
                :submitAction="{ show: true, toggle: true, span: 6 }"
                @onSubmit="onQuery"
                @onReset="onResetForm"
              />
            </a-form-model>
          </div>
        </a-card>
        <a-card :bordered="false">
          <!-- 操作按钮区域 -->
          <div class="table-operator">
            <div>
              <a-button @click="handleExport">导出</a-button>
            </div>
          </div>
          <!-- 表格展示 -->
          <div class="table-page-content">
            <z-table
              ref="table"
              rowKey="id"
              :showAlert="false"
              :showSelection="true"
              :loading="loading"
              :columns="columns"
              :dataSource="pageData"
              @change="onTableChange"
            />
          </div>
          <!--弹窗区域-->
          <handle-modal ref="handleModalRef" @ok="modalFormOk" />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as personServiceApi from '@/api/sjsk/personService'
import departTree from '../../modules/departTree'
import handleModal from '../../modules/handleModal'
import { downLoadFileReader } from '@/utils/export-util/util'

export default {
  components: { departTree, handleModal },
  data() {
    return {
      tabValue: 1,
      tabsItems: [
        { key: 1, title: '转入' },
        { key: 2, title: '转出' },
      ],
      loading: false,
      reloading: true,
      toggle: true,
      queryParam: {},
      fieldArr: [
        { label: '吸毒人员姓名', prop: 'name', tagType: 'input', span: 6 },
        { label: '吸毒人员身份证', prop: 'identityCard', tagType: 'input', span: 6 },
        { label: '人员类型', prop: 'personType', tagType: 'dict-select', dictCode: 'personType', span: 6 },
        { label: '性别', prop: 'sex', tagType: 'dict-select', dictCode: 'sex', span: 6, toggle: false },
        {
          label: '异地管控情况',
          prop: 'controlStatus',
          tagType: 'dict-select',
          dictOptions: [
            { text: '请选择', value: '' },
            { text: '异地管控', value: '1' },
            { text: '已撤销', value: '2' },
          ],
          span: 6,
          toggle: false,
        },
        { label: '是否结案', prop: 'isCloseCase', tagType: 'dict-select', dictCode: 'dict_yn', span: 6, toggle: false }
      ],
      columns: [
        {
          title: '姓名',
          dataIndex: 'realName',
          width: 60,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '性别',
          dataIndex: 'sex',
          width: 60,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={this.$filterDictTextByCache('sex', text)} length={14} />
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          width: 60,
          align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '人员类型',
          dataIndex: 'type',
          width: 60,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={this.$filterDictTextByCache('personType', text)} length={14} />
          }
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 60,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={text} length={14} />
          },
        },
        {
          title: '异地管控情况',
          dataIndex: 'controlStatus',
          width: 88,
          align: 'center',
          customRender: (text, record, index) => {
            return <span> {text === 1 ? '异地管控' : text === 2 ? '已撤销' : ''} </span>
          },
        },
        {
          title: '是否结案',
          dataIndex: 'isCloseCase',
          width: 90,
          align: 'center',
          customRender: (text) => {
            return <j-ellipsis value={this.$filterDictTextByCache('dict_yn', text)} length={14} />
          }
        },
        {
          title: '操作',
          width: 60,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            if(record.controlStatus===1 && this.tabValue==1) {
              return (
                <a-space size={6}>
                  <a-button type="link" style={'padding:0'} onClick={(event) => this.handleRouter(record)}> 查看 </a-button>
                  {record.belongManagerId ? (
                    <a-button type="link" style={'padding:0'} onClick={(event) => this.handleConfirm('remove-distribution', record)} > 解除分配 </a-button>
                  ) : (
                    <a-badge dot> 
                      <a-button type="link" style={'padding:0'} onClick={(event) => this.handleModal('personnel-assignment', record)} > 人员分配 </a-button>
                    </a-badge>
                  )}
                  <a-button
                    type="link"
                    style={'padding:0'}
                    disabled={
                      this.$options.filters.isDisabled('b', record.applyingLabel) ||
                      this.$options.filters.isDisabled('c', record.applyingLabel)
                    }
                    onClick={(event) => this.handleModal('cancel-remote-control', record)}
                  >
                    撤销异地管控
                  </a-button>
                </a-space>
              )
            } else {
              return <a-button type="link" style={'padding:0'} onClick={(event) => this.handleRouter(record)}> 查看 </a-button>
            }
          }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
    }
  },
  watch: {
    tabValue: {
      immediate: true,
      deep: true,
      handler(val) {
        let columnsIndex = this.columns.findIndex((item) => item.dataIndex === 'phone')
        let columns1 = { title: '户籍地专职人员', dataIndex: 'registerManager', width: 90, align: 'center' }
        let columns2 = { title: '户籍地区', dataIndex: 'registerDepartmentName', width: 110, align: 'center', customRender: (text) => <j-ellipsis value={text} length={10} />, }
        let columns3 = { title: '居住地区', dataIndex: 'departmentName', width: 110, align: 'center', customRender: (text) => <j-ellipsis value={text} length={10} />, }
        let columns4 = { title: '居住地专职人员', dataIndex: 'belongManager', width: 90, align: 'center' }
        let columns5 = { title: '居住地区', dataIndex: 'registerDepartmentName', width: 110, align: 'center', customRender: (text) => <j-ellipsis value={text} length={10} />, }
        let columns6 = { title: '户籍地区', dataIndex: 'departmentName', width: 110, align: 'center', customRender: (text) => <j-ellipsis value={text} length={10} />, }
        if (val == 1) {
          let dataIndex = this.columns.findIndex((item) => item.dataIndex === columns4.dataIndex)
          this.columns.splice(columnsIndex + 1, dataIndex > 0 ? 3 : 0, columns1, columns2, columns3)
        } else {
          let dataIndex = this.columns.findIndex((item) => item.dataIndex === columns1.dataIndex)
          this.columns.splice(columnsIndex + 1, dataIndex > 0 ? 3 : 0, columns4, columns5, columns6)
        }
      },
    },
    // 组织机构树-联动筛选人员列表
    'queryParam.departmentId'(newVal, oldVal){
      this.modalFormOk()
    }
  },
  created() {},
  async mounted() {
    this.onQuery()
  },
  methods: {
    changeTabs() {
      this.reload()
      this.onResetForm()
    },
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.queryParam = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      this.$set(this.queryParam, 'inOutType', this.tabValue)
      let queryParam = Object.assign({}, this.queryParam, this.pageFilter)
      this.loading = true
      personServiceApi
        .getSocialInsideList(queryParam)
        .then((res) => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.$message.warn(res.message ? res.message : '请求失败！')
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          querySocialInsideControlPersonVO: this.queryParam
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          personServiceApi.socialInsideExport(params).then(async res => {
            const fileName = '社会面有吸毒史人员-省内异地管控列表数据.xlsx'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    // 弹窗成功接收
    modalFormOk() {
      this.onQuery()
    },
    // 弹窗操作
    handleModal(key, record) {
      this.$refs.handleModalRef.show(key, record, this.queryParam.departmentId)
    },
    // 确认框操作
    handleConfirm(key, record) {
      let that = this
      let title = key === 'remove-distribution'? '人员解除分配':''
      let content = null
      this.$confirm({
        title: `确定${title}?`,
        content: h => content,
        onOk() {
          personServiceApi.socialRemoveDistribution(record.id).then((res) => {
            if (res.success) {
              this.$message.success(res.message?res.message:'操作成功')
            } else {
              this.$message.warn(res.message?res.message:'操作失败')
            }
          }).catch(e=>{
            this.$message.warn("操作失败！")
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'confirm',
      })
    },
    getSelectedKeys(keys) {
      console.log(keys)
      this.$set(this.form, 'labelId', keys.join(','))
      this.onQuery()
    },
    // 查看
    handleRouter(record) {
      let id = record instanceof Object ? record.id : record
      let path = id ? `/examine/details/2/${id}` : ``
      this.$router.push({
        path: path,
        query: {},
      })
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = false
      this.$nextTick(() => (this.reloading = true))
    },
    getTreeData(datas, id) {
      console.log(datas, id)
      console.log(id)
      this.$set( this.queryParam, 'departmentId', id )
    },
    toggleBool(bool) {
      this.toggle = bool
    },
  },
}
</script>
<style lang="less" scoped></style>
